﻿using Collection.Entities;
using Super.Collection.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Super.Collection.Core.Providers.Sports
{
    /// <summary>
    /// 乐彩网(http://baidu.lecai.com)
    /// </summary>
    public class LeCaiNet : DataProvider, IProvider
    {
        /// <summary>
        /// 公告数据正则表达式
        /// </summary>
        private string BriefingRegex
        {
            get
            {
                return @"<tr class=.bgcolor\d.>\W*?<td class=.td1.>(?'date'\d{4}-\d{2}-\d{2})</td>\W*?<td class=.td2.>\W*?<a href=./lottery/draw/view/1\?phase=\d{2,}.>(?'serialNumber'\d{2,})</a>\W*?</td>\W*?<td class=.td3.><span class=.result.>\W*?<span class=.ball_1.>(\d{2})</span>\W*?<span class=.ball_1.>(\d{2})</span>\W*?<span class=.ball_1.>(\d{2})</span>\W*?<span class=.ball_1.>(\d{2})</span>\W*?<span class=.ball_1.>(\d{2})</span>\W*?<span class=.ball_2.>(\d{2})</span>\W*?<span class=.ball_2.>(\d{2})</span>\W*?</span></td>\W*?<td class=.td4.>(?'sales'[\d|,]*?)</td>\W*?</tr>";
            }
        }

        /// <summary>
        /// 详情数据正则
        /// </summary>
        private string DetailsRegex1
        {
            get
            {
                return @"(?<=.1-1.:{.list.:{)(?'content'.*?)(?=},.result.)";
            }
        }

        /// <summary>
        /// 详情数据正则
        /// </summary>
        private string DetailsRegex2
        {
            get
            {
                return @"prize\d{1,}.:{.key.:.(prize\d{1,}).[\s\S]*?.bet.:.(?'quantity'\d{1,}).,.prize.:.(?'unitPrice'\d{1,}).";
            }
        }

        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="url">数据列表入口url</param>
        /// <param name="encoding">编码格式</param>
        /// <returns></returns>
        public override List<Announcement> GetAnnouncements(string url, Encoding encoding)
        {
            string detailUrl = "http://baidu.lecai.com/lottery/draw/view/1?phase={0}";
            List<Announcement> lotteryReports = new List<Announcement>();
            List<LotteryNumber> numbers;
            List<LotteryDetails> details;
            LotteryBriefing bulletin;
            string document = this.GetDocument(url, encoding);
            MatchCollection matchCollections = this.GetMatchCollections(document, this.BriefingRegex);
            for (int i = 0; i < matchCollections.Count; i++)
            {
                bulletin = this.GetLotteryBriefing(matchCollections[i]);
                numbers = this.GetLotteryNumbers(matchCollections[i]);
                details = this.GetLotteryDetails(string.Format(detailUrl, bulletin.SerialNumber), encoding, bulletin.SerialNumber);
                lotteryReports.Add(new Announcement
                {
                    LotteryBriefing = bulletin,
                    LotteryDetails = details,
                    LotteryNumbers = numbers
                });
            }
            return lotteryReports;
        }

        /// <summary>
        /// 从正则匹配的结果中创建中奖公告信息（部分）
        /// </summary>
        /// <param name="match">匹配结果项</param>
        /// <returns></returns>
        private LotteryBriefing GetLotteryBriefing(Match match)
        {
            string lotteryDate = match.Groups["date"].Value;
            string serialNumber = match.Groups["serialNumber"].Value;
            string sales = match.Groups["sales"].Value.Replace(",", string.Empty);
            LotteryBriefing briefing = new LotteryBriefing
            {
                LotteryDates = DateTime.Parse(lotteryDate),
                Provider = 2,
                LotteryTicketId = 2,
                Cumulative = 0.00m,
                SerialNumber = serialNumber,
                Sales = decimal.Parse(sales)
            };
            return briefing;
        }

        /// <summary>
        /// 获取中奖号码
        /// </summary>
        /// <param name="number"></param>
        /// <param name="blue">蓝色球</param>
        /// <returns></returns>
        private List<LotteryNumber> GetLotteryNumbers(Match match)
        {
            int length = 7;
            List<LotteryNumber> numbers = new List<LotteryNumber>();
            for (int i = 1; i <= length; i++)
            {
                numbers.Add(new LotteryNumber
                {
                    Location = (short)i,
                    Number = short.Parse(match.Groups[i].Value)
                });
            }
            return numbers;
        }


        /// <summary>
        /// 获取中奖详情
        /// </summary>
        /// <param name="url">提供者的地址</param>
        /// <param name="encoding">文档解析的编码</param>
        /// <returns>返回中奖详情列表</returns>
        private List<LotteryDetails> GetLotteryDetails(string url, Encoding encoding, string serialNumber)
        {
            string document = this.GetDocument(url, encoding);
            MatchCollection matchCollections = this.GetMatchCollections(document, this.DetailsRegex1.Replace("1-1", serialNumber));
            string content = string.Empty;
            foreach (Match match in matchCollections)
            {
                content = match.Groups["content"].Value;
            }
            return this.GetLotteryDetails(content);
        }

        /// <summary>
        /// 获取中奖详情
        /// </summary>
        /// <param name="url">提供者的地址</param>
        /// <param name="encoding">文档解析的编码</param>
        /// <returns>返回中奖详情列表</returns>
        private List<LotteryDetails> GetLotteryDetails(string content)
        {
            List<LotteryDetails> details = new List<LotteryDetails>();
            MatchCollection matchCollections = this.GetMatchCollections(content, this.DetailsRegex2);
            for (byte i = 0; i < matchCollections.Count; i++)
            {
                details.Add(new LotteryDetails
                {
                    RewardLevels = i++,
                    Quantity = int.Parse(matchCollections[i].Groups["quantity"].Value),
                    UnitPrice = int.Parse(matchCollections[i].Groups["unitPrice"].Value)
                });
            }
            return details;
        }

		public override NLotteryDraw GetLatestLotteryDraw()
		{
			throw new NotImplementedException();
		}
	}
}
